package com.example.finalhomework.cardgame

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.finalhomework.R
import java.io.File
import java.io.FileOutputStream


//设置底部导航栏的样式
@Composable
fun BottomNavigationBar(navController: NavHostController) {
    Log.d("FileUtils", "BottomNavigationBar Composable executed")
    // 创建底部导航栏
    NavigationBar (
        containerColor = Color.Black
    ){
        // 定义导航栏项目
        val items = listOf(
            BottomNavItem("PersonalInfo", R.drawable.baseline_home, "PersonalInfo"),
            BottomNavItem("CardGame", R.drawable.baseline_cardgame, "CardGame"),
            BottomNavItem("AdvancedCardGame", R.drawable.baseline_advancedcardgame, "AdvancedCardGame")
        )
        // 为每个导航栏项目创建NavigationBarItem
        val currentRoute = navController.currentBackStackEntryAsState().value?.destination?.route

        NavigationBar(containerColor = Color.Black) {
            items.forEach { item ->
                val isSelected = currentRoute == item.route
                NavigationBarItem(
                    icon = {

                        Icon(
                            painter = painterResource(id = item.icon),
                            contentDescription = item.label,
                            modifier = Modifier.size(if (isSelected) 30.dp else 24.dp), // Adjust the size of the Icon
                            tint = if (isSelected) Color.Black else Color.White // Change icon color if selected
                        )

                    },
                    label = { Text(item.label) },
                    selected = isSelected,
                    onClick = {
                        navController.navigate(item.route)
                        Log.d("FileUtils", "Navigated to ${item.route}")
                    },
                    colors = NavigationBarItemDefaults.colors(
                        selectedIconColor = Color.White,
                        unselectedIconColor = Color.White,
                        selectedTextColor = Color.White,
                        unselectedTextColor = Color.White,
                        indicatorColor = Color.White
                    )
                )
            }
        }
    }
}

//定义用户信息行的样式
@Composable
fun PersonalInfoRow(label: String, value: String) {
    Log.d("FileUtils", "PersonalInfoRow Composable executed with label: $label, value: $value")
    // 使用Row布局来水平排列组件
    Row(
        modifier = Modifier
            .padding(start = 30.dp) // 设置左边距
            .height(40.dp) // 设置高度
            .fillMaxWidth(), // 填充整个宽度
        verticalAlignment = Alignment.CenterVertically // 垂直居中对齐
    ) {
        // 使用Box布局来显示标签
        Box(
            modifier = Modifier.width(100.dp), // 设置宽度
            contentAlignment = Alignment.CenterEnd // 内容右对齐
        ) {
            Text(
                text = label, // 标签文本
                fontSize = 16.sp, // 字体大小
                textAlign = TextAlign.End // 文本右对齐
            )
        }
        Spacer(modifier = Modifier.width(20.dp)) // 添加水平间距
        // 显示值
        Text(
            text = value, // 值文本
            fontSize = 16.sp, // 字体大小
            textAlign = TextAlign.Start, // 文本左对齐
            modifier = Modifier.weight(1f) // 占据剩余空间
        )
    }
}

//保存图片到文件（修改图片时调用）
fun saveBitmapToFile(context: Context, bitmap: Bitmap, originalUri: Uri): Uri {
    val fileName = "avatar_${System.currentTimeMillis()}.png"   //创建带有时间戳的文件名
    val file = File(context.filesDir, fileName) //创建文件
    val fos = FileOutputStream(file)    //创建文件输出流
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)    //将图片压缩为PNG格式，质量为100，写入输出流
    fos.flush() //刷新输出流。输入流和输出流的区别在于输入流是读取数据，输出流是写入数据
    fos.close() //关闭输出流
    val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)  //获取文件URI

    val sharedPreferences = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE) //获取SharedPreferences
    sharedPreferences.edit().putString("avatar_uri", uri.toString()).apply()    //保存URI到SharedPreferences

    Log.d("UpdateInfoScreen", "Bitmap saved to file: $file, URI: $uri")     //打印日志

    return uri  //返回URI
}

//获取保存的图片URI（显示图片的时候调用）
fun getSavedImageUri(context: Context): Uri? {
    val sharedPreferences = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE) //获取SharedPreferences
    val uriString = sharedPreferences.getString("avatar_uri", null) //获取保存的URI
    Log.d("FileUtils", "Retrieved saved image URI: $uriString")
    return uriString?.let { Uri.parse(it) } //返回URI
}